package dsk.demo.product.config;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dsk.demo.product.entity.GuanggaoEntity;
import dsk.demo.product.entity.ProductEntity;
import dsk.demo.product.service.GuanggaoService;
import dsk.demo.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务配置
 */
@Component
public class TaskJobConfig {

    @Autowired
    private ProductService productService;

    @Autowired
    private GuanggaoService guanggaoService;

    private String url = "http://data.zz.baidu.com/urls?site=www.yinpeiauto.com&token=vDxQ2Xd5E5HjETx2";
    private String baseUrl = "http://yinpeiauto.com/page/detail/";

    /**
     * 每周六中午10点 制作网站地图     0 0 12 ? * SUN
     */
    @Scheduled(cron = "0 0 10 ? * 6")
    public void madeSiteMap() throws IOException {
        //删除源文件
        String fileName = File.separator + "mydata" + File.separator +
                "nginx" + File.separator + "html" + File.separator + "sitemap" + File.separator + "detailMapNew.txt";
//        String fileName = "F:\\uploadFile\\siteMap.txt";
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileWriter fileWriter = new FileWriter(file);
        String baseUrl = "http://yinpeiauto.com/page/detail/";
        Long index = 0l;
        int size = 100;
        int count = 0;
        int fileIndex = 0;
        while (true) {
            if (size >= 100) {
                if (count / 10000 > 0) {
                    count = 0;
                    fileWriter.close();
                    fileIndex++;
                    //删除源文件
                    fileName = File.separator + "mydata" + File.separator +
                            "nginx" + File.separator + "html" + File.separator + "sitemap" + File.separator + "detailMapNew" + fileIndex + ".txt";
                    file = new File(fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    fileWriter = new FileWriter(file);
                }
                QueryWrapper<ProductEntity> query = new QueryWrapper<>();
                query.select("id")
                        .gt("id", index)
                        .orderBy(true, true, "id")
                        .last("limit 100");
                List<ProductEntity> list = productService.list(query);
                if (list.size() > 0) {
                    index = list.get(list.size() - 1).getId();
                }
                size = list.size();
                StringBuilder sb = new StringBuilder();
                for (ProductEntity item : list) {
                    sb.append(baseUrl).append(item.getId()).append("\n");
                }
                //写入文件
                fileWriter.write(sb.toString());
                count += 100;
            } else {
                break;
            }
        }

        fileWriter.close();
    }

    /**
     * 每周日中午10点 清理没有引用的图片
     */
    @Scheduled(cron = "0 0 10 ? * 0")
    public void clearImage() throws IOException {
        File dir = new File(File.separator + "mydata" + File.separator + "nginx" + File.separator + "html" + File.separator + "images");
        Map<String, File> fileMap = new HashMap<>();
        listAllFile(dir, fileMap);

        //获取所有有用的图片
//        Set<String> fileNameSet = new HashSet<>();
//        fileNameSet.addAll(Arrays.asList(list));
        fileMap.remove("chenWeChat.png");
        fileMap.remove("chenWhatsApp.png");
        fileMap.remove("daiWeChat.png");
        fileMap.remove("daiWhatsApp.png");
        //1.获取广告轮播图
        for (GuanggaoEntity guanggaoEntity : guanggaoService.list()) {
            if (StrUtil.isNotBlank(guanggaoEntity.getUrl())) {
                fileMap.remove(getFileNmaeFromUrl(guanggaoEntity.getUrl()));
            }
        }

        Long index = 0l;
        int size = 100;
        while (true) {
            if (size >= 100) {
                QueryWrapper<ProductEntity> query = new QueryWrapper<>();
                query.select("id", "image", "image1", "image2", "image3", "image4", "image5")
                        .gt("id", index)
                        .orderBy(true, true, "id")
                        .last("limit 100");
                List<ProductEntity> productList = productService.list(query);
                if (productList.size() > 0) {
                    index = productList.get(productList.size() - 1).getId();
                }
                size = productList.size();
                for (ProductEntity productEntity : productList) {
                    if (StrUtil.isNotBlank(productEntity.getImage())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage()));
                    }
                    if (StrUtil.isNotBlank(productEntity.getImage1())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage1()));
                    }
                    if (StrUtil.isNotBlank(productEntity.getImage2())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage2()));
                    }
                    if (StrUtil.isNotBlank(productEntity.getImage3())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage3()));
                    }
                    if (StrUtil.isNotBlank(productEntity.getImage4())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage4()));
                    }
                    if (StrUtil.isNotBlank(productEntity.getImage5())) {
                        fileMap.remove(getFileNmaeFromUrl(productEntity.getImage5()));
                    }
                }
            } else {
                break;
            }
        }
        System.out.println("当前无用的图片列表:" + fileMap);
        //删除所有无用的数据
        for (Map.Entry<String, File> stringFileEntry : fileMap.entrySet()) {
            if (!stringFileEntry.getValue().isDirectory()) {
                boolean delete = stringFileEntry.getValue().delete();
                System.out.println("删除图片:" + stringFileEntry.getKey() + "    " + delete);
            }
        }
    }

    private String getFileNmaeFromUrl(String url) {
        String[] split = url.split("\\/");
        return split[split.length - 1];
    }

    private void listAllFile(File dir, Map<String, File> map) {
        for (File file : dir.listFiles()) {
            if (!file.isDirectory()) {
                map.put(file.getName(), file);
            } else {
                listAllFile(file, map);
            }
        }
    }

//    public void createContentToFacebookGroup() {
//
//        String dskPageId = "100040180920757";
//
//        String url = "https://graph.facebook.com/v20.0/1562830094231640/feed";
//        HashMap<String, String> params = new HashMap<>();
//        params.put("message", "Test");
//        params.put("link", "http://yinpeiauto.com");
//        HttpUtil.post(url, JSONUtil.toJsonStr(params));
//
//    }

}
